package com.lijinjiang.reflect03_field;

import org.junit.Test;

import java.lang.reflect.Field;

/**
 * @ClassName TestField02
 * @Description TODO
 * @Author Li
 * @Date 2022/9/20 21:12
 * @ModifyDate 2022/9/20 21:12
 * @Version 1.0
 */
public class TestField02 {
    @Test
    public void testSetField() throws Exception {
        // 1.获取class对象
        Class c = Student.class;
        // 2.获取指定成员变量
        Field field = c.getDeclaredField("age");
        field.setAccessible(true);
        // 3.赋值
        Student stu01 = new Student();
        field.set(stu01, 18);
        System.out.println(stu01);

        // 4.取值
        Student stu02 = new Student("李四", 27);
        int age = (int) field.get(stu02);
        System.out.println(age);
    }
}
